package com.lk.recvice.server.netty;

import com.alibaba.fastjson.JSONObject;
import com.lk.base.mysql.domain.TblDevices;
import com.lk.recvice.server.MyServerSocket;
import com.lk.recvice.server.MySocketChannel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyServerHandler extends SimpleChannelInboundHandler<String>{

	static Logger logger = LoggerFactory.getLogger(MyServerHandler.class);
	private SocketChannel sc;

	public MyServerHandler(SocketChannel sc) {
		this.sc = sc;

	}


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String hexcontent) throws Exception {
		//打印出客户端地址
		logger.debug("================["+ctx.channel().remoteAddress()+"]数据上传:["+hexcontent+"]===============");

    }

	/**
	 * 处理设备接受的数据
	 * @param ctx
	 * @param deviceIp
	 * @param str
	 */
	private void handleDatas(ChannelHandlerContext ctx, String deviceIp, String str) throws  Exception{
		if("04".equals(MyServerSocket.gasMaps.get(deviceIp).getProtocolType())){ //TCP

			boolean rs = getTcpEntity(ctx, deviceIp, str);
			if (!rs) return;
			this.doSaveRedis(deviceIp);

		}
	}

	/**
	 * 远程设备过来数据后进行保存redis
	 * @param deviceIp
	 */
	private void doSaveRedis(String deviceIp) {
		TblDevices entityVO = MyServerSocket.gasMaps.get(deviceIp);
		if(entityVO == null){
			logger.debug("IP["+deviceIp+"]对应的设备不存在，无法获取相应的对象");
			return;
		}

		String deviceSnId = entityVO.getId();
		String jsonData = JSONObject.toJSONString(entityVO);
//		messageSender.doSaveRemoteDeviceDatas(deviceSnId, jsonData);

	}






	/**
	 * TCP
	 * @param ctx
	 * @param deviceIp
	 * @param str
	 * @return
	 */
	private boolean getTcpEntity(ChannelHandlerContext ctx, String deviceIp, String str) {
		TblDevices entityVO = MyServerSocket.gasMaps.get(deviceIp);
		if(entityVO == null){
			logger.debug("IP["+deviceIp+"]对应的设备不存在，无法获取相应的对象");
			return false;
		}
//		String deviceSnId = entityVO.getSnId();
//		TblDevices deviceEntity = MyServerSocket.deviceMaps.get(deviceSnId);
//		logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<设备上线后接收日志啦---------设备号：["+deviceSnId+"];"+str);
//		if (deviceEntity!=null){
//			if(!StringUtil.isNullOrEmpty(deviceEntity.getPackageHead()) && !StringUtil.isNullOrEmpty(deviceEntity.getPackageEnd())){
//				if(str.startsWith(deviceEntity.getPackageHead()) && str.endsWith(deviceEntity.getPackageEnd())) {
//					MyServerSocket.strMap.put(deviceIp, str);
//					logger.debug("数据["+str+"]未被拆包[状态正常]长度["+str.length()+"]");
//				}else {
//					String strRomt = MyServerSocket.strMap.get(deviceIp)==null?"":MyServerSocket.strMap.get(deviceIp);
//					if(StringUtil.isNullOrEmpty(str)){
//						strRomt = "";
//					}
//					strRomt += str;
//					MyServerSocket.strMap.put(deviceIp, strRomt);
//					logger.debug("数据["+str+"]已被拆包[状态异常]当前长度["+str.length()+"]，当前粘包数据["+strRomt+"]长度["+strRomt.length()+"]");
//					if(!(strRomt.endsWith(deviceEntity.getPackageEnd()))){
//						return false;
//					}
//					logger.debug("数据["+str+"]已被拆包[粘包完成]当前长度["+str.length()+"]，当前粘包数据["+strRomt+"]长度["+strRomt.length()+"]");
//				}
//			}else {
//				MyServerSocket.strMap.put(deviceIp, str);
//			}
//
//
//			String protocolType = deviceEntity.getProtocolType();
//			String handleType = Constant.ProtocolType.getLabel(protocolType);
//			OtaManager manager = OtaManagerBuilder.getInstance().build(handleType);
//			manager.init().doWork(MyServerSocket.strMap.get(deviceIp).replaceAll(" ",""), ctx,deviceSnId);
//		}
//		MyServerSocket.strMap.remove(deviceIp);
		return true;
	}

	/**
	 * 发送设备其余的命令
	 * @param
	 * @return
	 * @throws InterruptedException
	 */
	@Deprecated
//	public boolean sendRules(String deviceIp) throws InterruptedException {
//		EntityVO entityVO = MyServerSocket.gasMaps.get(deviceIp);
//		TblDevices deviceEntity = MyServerSocket.deviceMaps.get(entityVO.getSnId());
//		Thread.sleep(500);
//		Map<String, List<String>> sendRuleMaps = deviceEntity.getSendRuleMaps();
//		List<String> slaveAddrs = deviceEntity.getSlaveAddrs();
//
//		ByteBuf resp=null;
//		int slAddrLength = slaveAddrs.size();
//		int slaveAddressIndex = deviceEntity.getSlaveAddressIndex();
//		int ruleIndex = deviceEntity.getRuleIndex();
//
//		String key = slaveAddrs.get(slaveAddressIndex);
//		int everySlaveAddrsRulesLen = sendRuleMaps.get(key).size();
//
//		String rule = sendRuleMaps.get(key).get(ruleIndex);
//		resp= Unpooled.copiedBuffer(CrcUtils.hexStringToByte(rule));//历史数据
//		logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>ip["+deviceIp+"];"+deviceEntity.getProtocolType()
//				+"设备["+deviceEntity.getSnId() +"]开始下发第"+ruleIndex+"条命令：["+rule+ "]") ;
//
//		sc.writeAndFlush(resp).addListener(new ChannelFutureListener() {
//			@Override
//			public void operationComplete(ChannelFuture future) {
//				if(future.isSuccess()){
//					int slaveAddressIndex = deviceEntity.getSlaveAddressIndex();
//					int ruleIndex = deviceEntity.getRuleIndex();
//
//					//所有从机地址都发送完命令了
//					if( slaveAddressIndex >= slAddrLength-1 && ruleIndex >= everySlaveAddrsRulesLen - 1){
//						deviceEntity.setRuleIndex(0);
//						deviceEntity.setSlaveAddressIndex(0);
//						//每个从机地址中的命令是否走到了最后一条
//					}else if(ruleIndex >= everySlaveAddrsRulesLen - 1){
//						deviceEntity.setSlaveAddressIndex(++slaveAddressIndex);
//						deviceEntity.setRuleIndex(0);
//						logger.debug("");
//					}else{
//						deviceEntity.setRuleIndex(ruleIndex+1);
//					}
//
//				}
//				logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>ip["+sc.remoteAddress()+"];协议["+deviceEntity.getProtocolType()+"]从机地址["
//						+slaveAddressIndex+"]设备["+deviceEntity.getSnId()
//						+"]开始下发第"+(ruleIndex+1)
//						+"条命令：["+sendRuleMaps.get(key).get(ruleIndex)+ "]"+"######"+future.isSuccess());
//			}
//		});
//
//		return false;
//	}




    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {

//		MyServerSocket.sockets.remove(ctx.channel().id().toString());

//		MySocketChannel mySocketChannel = MyServerSocket.socketChannel_keepalive.get(ctx.channel().id().toString());
//		logger.debug("====================设备["+mySocketChannel.getSnId()+"]["+ctx.channel().remoteAddress()+"]channel 不活跃，断开连接===================");
//		if(mySocketChannel != null) {
//			if(mySocketChannel.getSnId() != null) {
//				String protocolType = MyServerSocket.deviceMaps.get(mySocketChannel.getSnId()).getProtocolType();
//				String handleType = Constant.ProtocolType.getLabel(protocolType);
//				OtaManager manager = OtaManagerBuilder.getInstance().build(handleType);
//				manager.init().doOffline(mySocketChannel.getSnId());
//			}
//		}
//
//		MyServerSocket.removeMySocketChannel_keepalive(ctx.channel().id().toString());
//		MyServerSocket.gasMaps.remove(MyServerSocket.gasMaps.get(ctx.channel().remoteAddress().toString()));
//		super.channelInactive(ctx);
	}


	/**
	 * 重置上限设备各种属性
	 * @param channelId
	 * @param deviceIp
	 * @param deviceEntity
	 */
    public void resetSocket(String channelId,String deviceIp,TblDevices deviceEntity) {
    	String deviceSnId = deviceEntity.getId();
    	logger.debug("=================["+channelId+"]["+deviceIp+"]["+deviceSnId+"]上线====================");
    	new Thread(new Runnable() {

			@Override
			public void run() {
				MySocketChannel mySocketChannel = MyServerSocket.socketChannel_keepalive.get(channelId);
		        mySocketChannel.setSnId(deviceSnId);
		        MyServerSocket.socketChannel_keepalive.put(channelId, mySocketChannel);

		        for (MySocketChannel tmp : MyServerSocket.socketChannelList_keepalive) {
					if(tmp.getSocketChannel().id().toString().equals(deviceSnId)) {
						tmp.setSnId(deviceSnId);
					}
				}
			}
		}).start();

		String ip = MyServerSocket.snFindIpMap.get(deviceSnId);
		if(ip != null){
			MyServerSocket.gasMaps.remove(ip);
		}

		MyServerSocket.snFindIpMap.put(deviceSnId,deviceIp);
		TblDevices gasEntity = new TblDevices();
		gasEntity.setIp(deviceIp);
		gasEntity.setProtocolType(deviceEntity.getProtocolType());
		gasEntity.setId(deviceSnId);
		MyServerSocket.gasMaps.put(deviceIp,gasEntity);
//
//		MyServerSocket.deviceMaps.get(deviceSnId).setRuleIndex(0);
//		MyServerSocket.deviceMaps.get(deviceSnId).setSlaveAddressIndex(0);
    }

}
